package com.comum.javahomework420242025.controller;

import com.comum.javahomework420242025.pojo.*;
import com.comum.javahomework420242025.repository.ChanceRepository;
import com.comum.javahomework420242025.repository.ClientComeRepository;
import com.comum.javahomework420242025.repository.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ClientController {
    @Autowired
    private ClientRepository clientRepository;
    @Autowired
    private ClientComeRepository clientComeRepository;
    @Autowired
    private ChanceRepository chanceRepository;
    @PostMapping("/addClient")
    public Result addclient(@RequestBody ClientCompany clientCompany){
        System.out.println(clientCompany);
        ClientCompany f = clientRepository.existsByClientRepository(clientCompany.getClientcompanyname());
        if(f!=null)return Result.error("客户名称存在！");
        clientCompany.setId(null);
        clientRepository.save(clientCompany);
        return Result.success();
    }
    @PutMapping("/updateClient")
    public Result updateClient(@RequestBody ClientCompany clientCompany){
        ClientCompany f = clientRepository.existsByClientRepository(clientCompany.getClientcompanyname());
        System.out.println("::::"+f);
        System.out.println("::::2"+clientCompany);
        System.out.println(f.getId()!=clientCompany.getId());
        System.out.println(f.getId().equals(clientCompany.getId()));
        if(f!=null&&!f.getId().equals(clientCompany.getId())) return Result.error("客户名称存在！");
        clientRepository.save(clientCompany);
        return Result.success();
    }
    @PostMapping("/getClient")
    public Result<PageBean<ClientCompany>> getUser(@RequestBody AskList askList){
        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        String str = askList.getStr();
        PageBean<ClientCompany> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<ClientCompany> page = clientRepository.selectByStr(str,pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());
        return Result.success(pb);
    }
    @DeleteMapping("/deleteClient")
    public Result deleteClient(String id){
        System.out.println(id);
        List<ClientCome> res = clientComeRepository.findByClientId(id);
        List<Chance> res2 = chanceRepository.findByClientId(id);
        if(res.size()!=0||res2.size()!=0) return Result.error("该客户存在其他信息关联，无法删除！");
        clientRepository.deleteById(Long.valueOf(id));
        return Result.success();
    }

    @GetMapping("/getAllClient")
    public Result getAllClient() {
        return Result.success(clientRepository.findAll());
    }
}
